import {message} from 'antd';
import type {RcFile} from 'antd/es/upload/interface';
import {visitUrlPrefix} from './IpUtil';
import {request} from '@umijs/max';

/**
 * 验证上传的文件是否为图片并且符合规定大小
 * @param file 要验证的文件
 * @param maxSize 最大文件大小（MB），默认为10MB
 * @return boolean
 */
export function verifyImage(file: RcFile, maxSize: number = 10): boolean {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    message.error('只能上传图片文件!');
    return false;
  }
  const isLtMaxSize = file.size / 1024 / 1024 < maxSize;
  if (!isLtMaxSize) {
    message.error(`图片必须小于 ${maxSize}MB!`);
    return false;
  }
  return true;
}

/**
 * 将对象转换为FormData
 * @param obj 要转换的对象
 * @returns FormData
 */
export function objectToFormData(obj: Record<string, any>): FormData {
  const formData = new FormData();
  Object.entries(obj).forEach(([key, value]) => {
    if (value instanceof File) {
      formData.append(key, value);
    } else if (value !== null && value !== undefined) {
      formData.append(key, String(value));
    }
  });
  return formData;
}

/**
 * 获取完整的图片URL
 * @param img 图片路径
 * @returns 完整的图片URL
 */
export function getFullImageUrl(img?: string): string | undefined {
  if (!img) return undefined;
  if (img.startsWith('http') || img.startsWith('https')) return img;
  const url = `${visitUrlPrefix()}/${process.env.API_PREFIX || ''}`;
  return `${url}${img}`;
}

/**
 * 字节转MB
 * @param bytes 字节数
 * @returns 格式化后的MB字符串
 */
export function bytesToMB(bytes: number): string {
  const mb = bytes / (1024 * 1024);
  return `${mb.toFixed(2)} MB`;
}

interface DownloadOptions {
  url: string;
  method?: 'GET' | 'POST';
  params?: Record<string, any>;
  data?: any;
  fileName?: string;
  onProgress?: (percent: number) => void;
}

/**
 * UmiJS Max 兼容的通用文件下载函数
 * @param options 下载选项
 * @returns Promise<void>
 */
export async function umiFileDownload(options: DownloadOptions): Promise<void> {
  const {
    url: originalUrl, // 修改变量名为 originalUrl 以避免与后续声明的局部变量冲突
    method = 'GET',
    params,
    data,
    fileName: userFileName,
    onProgress
  } = options;

  try {
    const response = await request<Blob>(originalUrl, {
      method,
      params,
      data,
      timeout: -1,
      responseType: 'blob',
      getResponse: true,
      ...(onProgress && {
        onDownloadProgress: (event: ProgressEvent) => {
          const percent = event.total
            ? Math.round((event.loaded * 100) / event.total)
            : 0;
          onProgress(percent);
        }
      }),
    });

    // 正确处理 request 函数的返回值
    const { data: blobData, headers } = response;

    // 尝试从响应头获取文件名
    const contentDisposition = headers['content-disposition'] as string | undefined;
    let fileName = userFileName;
    if (contentDisposition) {
      const fileNameMatch = contentDisposition.match(/filename="?(.+)"?/i);
      if (fileNameMatch) {
        fileName = fileNameMatch[1];
      }
    }
    fileName = fileName || 'download';

    // 使用 File API 创建文件并下载
    const blob = new Blob([blobData], { type: headers['content-type'] || 'application/octet-stream' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = fileName;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  } catch (error) {
    console.error('Download failed:', error);
    message.error('文件下载失败，请稍后重试。');
    throw error;
  }
}

// 使用示例
// umiFileDownload({
//   url: '/api/dbBackup/files/download',
//   params: { id: 123, fileName: 'backup.zip' },
//   fileName: 'my_backup.zip',
//   onProgress: (percent) => {
//     console.log(`Download progress: ${percent}%`);
//   }
// });
